package com.maizhi.util;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

import org.apache.log4j.Logger;

public class PropertiesUtil {
	
	private Logger logger  = Logger.getLogger(PropertiesUtil.class);
	private String info    = "classPath:info.properties";
	private Properties  pp = new Properties();
	
	public PropertiesUtil(){
		String classPath = this.getClass().getResource("/").getPath().replaceAll("%20", " ");
		String conf = info.replace("classPath:", classPath);
		File ppFile = new File(conf);
		if(ppFile.exists()){
			try {
				pp.load(new FileInputStream(ppFile));
				logger.debug("load file classPath:info.properites success");
			} catch (FileNotFoundException e) {
				logger.error("classPath:info.properties File not exist");
			} catch (IOException e) {
				logger.equals("load File info.properties error");
			}
		}
	}
	
	public PropertiesUtil(String configPath){
		this.info=configPath;
		String classPath = this.getClass().getResource("/").getPath().replaceAll("%20", " ");
		String conf = configPath.replace("classPath:", classPath);
		File ppFile = new File(conf);
		
		if(ppFile.exists()){
			try {
				pp.load(new FileInputStream(ppFile));
				logger.debug("load file "+configPath+" success");
			} catch (FileNotFoundException e) {
				logger.error(configPath+" File not exist");
			} catch (IOException e) {
				logger.equals("load File "+configPath+" error");
			}
		}
	}
	
	public String getByKey(String key){
		String val = nullTrim(key).equals("")?"":pp.getProperty(key);
		String res="";
		try {
			res = new String(val.getBytes("iso-8859-1"),"utf-8");
		} catch (Exception e) {
			if(this.info.equals("classPath:info.properties")){
				res = getByKey("?");	
			}else{
				res = e.getMessage();
			}
		}
		return res;
	}
	
	public String nullTrim(Object obj){
		String res="";
		if(!(obj==null || obj.equals(""))){
			res = obj.toString().trim();
		}
		return res;
	}
	
	
	public static void main(String[] args){
		PropertiesUtil ppu = new PropertiesUtil("classPath:info.Properties");
		ppu.pp.setProperty("test","中国");
		
		
		System.out.println(ppu);
		System.out.println(ppu.getByKey("test"));
	}
}










